package com.huang.exception;

import com.huang.resp.CommonResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author han
 * @since 2022-02-18 09:34:14
 */
@Log4j2
@RestControllerAdvice
public class GlobalExceptionHandling {

    /**
     * 自定义异常
     */
    @ExceptionHandler(value = BizException.class)
    public Map<String, Object> customException(BizException e) {
        log.error(e.getMsg());
        Map<String, Object> map = new HashMap<>(2);
        map.put("code", e.getCode());
        map.put("msg", e.getMsg());
        return map;
    }

    /**
     * 通用异常
     */
    @ExceptionHandler(Exception.class)
    public Map<String, Object> exception(Exception e) {
        e.printStackTrace();
        log.error("通用异常：{}", e.getMessage());
        Map<String, Object> map = new HashMap<>(2);
        map.put("code", 500);
        map.put("msg", e.getMessage());
        return map;
    }

    //处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public CommonResult BindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().
                map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return CommonResult.error(message);
    }

    //处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public CommonResult ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining());
        return CommonResult.error(message);
    }

    //处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常。
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining());
        return CommonResult.error(message);
    }

}
